package com.amado.easyui2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.amado.easyui2.constant.GlobalConstants;
import com.amado.easyui2.domain.User;
import com.amado.easyui2.exception.ApiException;
import com.amado.easyui2.service.UserService;
import com.amado.easyui2.util.ArrayUtil;
import com.amado.easyui2.util.JsonUtil;
import com.amado.easyui2.util.Md5Util;
import com.amado.easyui2.util.SessionUtils;
import com.amado.easyui2.vo.Page;
import com.amado.easyui2.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UserServlet extends HttpServlet {
//	private UserService userService = new UserServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	private static final long serialVersionUID = 1L;
	UserService userService;
	ApplicationContext applicationContext;

	@Override
	public void init() throws ServletException {
		// Spring容器
		applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		// 通过容器获取Bean
		userService = applicationContext.getBean("userServiceImpl", UserService.class);
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setHeader("Content-type", "text/html;charset=UTF-8");
		String method = arg0.getParameter("method");
		if ("add".equals(method)) {
			add(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("update".equals(method)) {
			update(arg0, arg1);
		} else if ("login".equals(method)) {
			// login(arg0, arg1);
		} else if ("loginOut".equals(method)) {
			// loginOut(arg0, arg1);
		}
//		else if ("getByUserName".equals(method)) {
//			getByUserName(arg0, arg1);
//		}
	}

//	private void getByUserName(HttpServletRequest arg0, HttpServletResponse arg1) {
//		String userName = arg0.getParameter("userName");
//		userService.getByUserName(userName);
//		if (userName.equals(userName) && userName != null) {
//			System.out.println("用户名已存在，请重新输入");
//		}
//	}

	protected void add(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		try {
			String strJson = arg0.getParameter("data");
			User userInfo = JsonUtil.jsonToBean(strJson, User.class);
			String loginUser = SessionUtils.getUserName(arg0);
			userInfo.setCreateName(loginUser);
			userInfo.setUpdateName(loginUser);
			// 对密码进行md5加密
			userInfo.setPassword(Md5Util.encode(userInfo.getPassword()));
			userService.add(userInfo);
			arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
		} catch (ApiException e) {
			arg1.getWriter().print(JsonUtil.beanToJson(new Result(e.getCode(),e.getMessage())));
		}catch (Exception e) {
			e.printStackTrace();
			arg1.getWriter().print(JsonUtil.beanToJson(new Result("0", "系统异常,请联系管理员")));
		}
	}

	protected void query(HttpServletRequest arg0, HttpServletResponse resp) throws IOException {
		// int currentPage = 1;
		Page page = new Page();
		String strPage = arg0.getParameter("page");
		String strRows = arg0.getParameter("rows");
		int page1 = strPage == null ? 1 : Integer.parseInt(strPage);//
		int rows = strRows == null ? 5 : Integer.parseInt(strRows);
		String name = arg0.getParameter("userNum");
		String departmentNum = arg0.getParameter("departmentNum");
		page.setCurrentPage(page1);
		page.setRowSize(rows);
		Page<User> pageList = userService.listAll(name, departmentNum, page);
		PrintWriter out = resp.getWriter();
		out.print(mapper.writeValueAsString(pageList));
	}

	protected void delete(HttpServletRequest arg0, HttpServletResponse resp) throws IOException {
		String ids = arg0.getParameter("ids");
		if (ids != null && ids.trim() != "") {
			
			try {
				String[] stringIdArray = ids.split(",");
				Long[] longIdArray = ArrayUtil.StringToInt(stringIdArray);
				userService.delete(longIdArray);
				resp.getWriter().print(JsonUtil.beanToJson(new Result()));
			} catch (ApiException e) {
				resp.getWriter().print(JsonUtil.beanToJson(new Result(e.getCode(),e.getMessage())));
			} catch (Exception e) {
				e.printStackTrace();
				resp.getWriter().print(JsonUtil.beanToJson(new Result("2","系统异常请联系管理员")));
			}
			
		} else {
			resp.getWriter().print(JsonUtil.beanToJson(new Result("0", "参数错误")));
		}
	}

	protected void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		List<User> list = userService.list();
		for (User user : list) {
			if (user.getId().equals(id)) {
				User userId = user;
				PrintWriter out = arg1.getWriter();
				out.print(mapper.writeValueAsString(userId));
				break;
			}
		}
	}

	protected void update(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");// 解析
		User userInfo = JsonUtil.jsonToBean(strJson, User.class);
		String updateName = SessionUtils.getUserName(arg0);
		userInfo.setUpdateName(updateName);
		userService.update(userInfo);
	}

	protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		User userInfo = new User(userName, password);
		String verifyCode = req.getParameter("VerificationCode");
		String sessionVerifyCode = (String) req.getSession(true).getAttribute(verifyCode);
		if (sessionVerifyCode != null && sessionVerifyCode.equals(verifyCode)) {
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			return;
		}
		List<User> list = userService.getUserName(userInfo);
		if (list != null) {
			list.forEach(e -> {
				if (e.getUserNum() != null && !e.getUserNum().equals("") && e.getPassword() != null
						&& !e.getPassword().equals("")) {
					req.getSession().setAttribute(GlobalConstants.SESSION_USER, userName);
					try {
						resp.sendRedirect("index.jsp");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					req.setAttribute("msg", "用户名或密码错误");
					try {
						req.getRequestDispatcher("login.jsp").forward(req, resp);
					} catch (ServletException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
			// for (int i = 0; i < list.size(); i++) {
			// User user = list.get(i);
			// if(user.getUserNum()!=null && !user.getUserNum().equals("") &&
			// user.getPassword()!=null && !user.getPassword().equals("")) {
			// req.getSession().setAttribute(GlobalConstants.SESSION_USER, userName);
			// // 退出登录
			// // req.getSession().removeAttribute(GlobalConstants.SESSION_USER);
			// resp.sendRedirect("index.jsp");
			// }
			// }
			// }
			// else
			// {
			// req.setAttribute("msg", "用户名或密码错误");
			// req.getRequestDispatcher("login.jsp").forward(req, resp);
			// }
		}

	}

	protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getSession().removeAttribute(GlobalConstants.SESSION_USER);
		resp.sendRedirect("login.jsp");
	}
}
